<?php


namespace App\Services;


class EsConnector //提供ES连接
{
    private static $elasticsearch;

    public function __construct()
    {
        if (self::$elasticsearch == null){
            self::$elasticsearch = self::buildInstance();
        }
    }

    private function buildInstance(){
        $array = [
            'host'     => config('app.es_host'),
            'port'     => config('app.es_port')
        ];
        if (config('app.es_user') && config('app.es_pass')){
            $array['username'] = config('app.es_user');
            $array['password'] = config('app.es_pass');
        }
        $config = new \EasySwoole\ElasticSearch\Config($array);
        return new \EasySwoole\ElasticSearch\ElasticSearch($config);
    }

    /**
     * @return \EasySwoole\ElasticSearch\ElasticSearch
     */
    public static function getInstance(){
        if (self::$elasticsearch){
            return self::$elasticsearch;
        } else {
            self::$elasticsearch = self::buildInstance();
        }
        return self::$elasticsearch;
    }
}
